package cn.liangjintang.webserver;

import java.lang.reflect.Method;
import java.net.InetAddress;

public class IP {
    InetAddress address;

    public IP(InetAddress address) {
        this.address = address;
    }

    public InetAddress getRaw() {
        return address;
    }

    public String getRawIP() {
        String ip = getIp();
        int index = ip.indexOf('%');
        return index < 0 ? ip : ip.substring(0, index);
    }

    public String getIp() {
        return address.getHostAddress();
    }

    public boolean isV6() {
        return !Utils.IPisCorrect(getIp());
    }

    public boolean isV4() {
        return Utils.IPisCorrect(getIp());
    }

    public String getType() {
        if (address.isLinkLocalAddress()) {
            return "链路本地地址";
        }
        if (address.isSiteLocalAddress()) {
            return " 站点本地地址";
        }
        if(isCommonIP(address)){
            return " 普通IP地址(一般为公网IP)";
        }
        return "未知类型";
    }

    public String getInterFaceTag() {
        String ip = getIp();
        int index = ip.indexOf('%');
        return index < 0 ? "" : ip.substring(index + 1);
    }

    public String getHttpUrl(String scheme, int port, String path) {
        String rawIP = getRawIP();
        String temp = isV6() ? ("[" + rawIP + "]") : rawIP;
        return scheme + temp + ":" + port + path;
    }

    public String getHttpUrl(String scheme, String path) {
        String rawIP = getRawIP();
        String temp = isV6() ? ("[" + rawIP + "]") : rawIP;
        return scheme + temp + path;
    }

    public static boolean isCommonIP(InetAddress address) {
        Method methods[] = InetAddress.class.getMethods();
        // 以is开头并且没有参数的方法
        for (Method method : methods) {
            if (method.getName().matches("is.*") && method.getParameterTypes().length == 0) {
                try {
                    if (Boolean.parseBoolean(method.invoke(address).toString()))
                        return false;
                } catch (Exception e) {

                }
            }
        }
        return true;
    }
}

